package moment

import (
	"fmt"
	"time"
)

type Duration time.Duration

const (
	Millisecond = Duration(time.Millisecond)
	Second      = Duration(time.Second)
	Minute      = Duration(time.Minute)
	Hour        = Duration(time.Hour)
	Day         = 24 * Hour
)

func (d Duration) Nanoseconds() int64 {
	return time.Duration(d).Nanoseconds()
}

func (d Duration) Microseconds() int64 {
	return time.Duration(d).Microseconds()
}

func (d Duration) Milliseconds() int64 {
	return time.Duration(d).Milliseconds()
}

func (d Duration) Seconds() float64 {
	return time.Duration(d).Seconds()
}

func (d Duration) Minutes() float64 {
	return time.Duration(d).Minutes()
}

func (d Duration) Hours() float64 {
	return time.Duration(d).Hours()
}

// 格式化成可读字符, 最小单位到毫秒
func (d Duration) Format(needMilliseconds bool) (elapse string) {
	return d.format("小时", "分", "秒", needMilliseconds)
}

// 格式化成可读字符, 最小单位到毫秒
func (d Duration) FormatEn(needMilliseconds bool) (elapse string) {
	return d.format("h", "m", "s", needMilliseconds)
}

func (d Duration) format(hour, min, sec string, needMilliseconds bool) (elapse string) {
	diff := time.Duration(d).Milliseconds()
	if diff < 0 {
		return
	}

	h := diff / time.Hour.Milliseconds()
	if h > 0 {
		elapse += fmt.Sprintf("%d%s", h, hour)
	}

	m := (diff % time.Hour.Milliseconds()) / time.Minute.Milliseconds()
	if h > 0 || m > 0 {
		elapse += fmt.Sprintf("%d%s", m, min)
	}

	s := (diff % time.Minute.Milliseconds()) / time.Second.Milliseconds()
	ms := diff % time.Second.Milliseconds()

	if needMilliseconds {
		elapse += fmt.Sprintf("%d.%d%s", s, ms, sec)
	} else {
		elapse += fmt.Sprintf("%d%s", s, sec)
	}

	return
}
